import axios from "axios";
import { ElMessage } from "element-plus";
import { get } from "lodash-es";
import store from "@/store";
import { router } from "@/router";
const { VITE_BASE_URL, VITE_PREFIX } = import.meta.env;
const config = {
  baseURL: VITE_BASE_URL,
  // baseURL: '/api',
  timeout: 1000,
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
  },
};

const api = axios.create(config);


// 默认 post 请求，使用 application/json 形式
api.defaults.headers.post["Content-Type"] = "application/json";

//封装下post
api.post = function (url, params, headers) {
  const token = sessionStorage.getItem("token")?.replace(/^(\s|")+|(\s|")+$/g, "");
  return new Promise((resolve, reject) => {
    axios({
      method: "POST",
      url: config.baseURL + url,
      data: params,
      'responseType': url === '/evidence/file/decrypt' ? 'blob' : null,
      headers: headers ? {
        ...headers,
        Authorization: token
      } : {
        "Content-Type": "application/json",
        ...(url.includes("login") || url.includes("notice")
          ? {}
          : { Authorization: token }),
      },
    })
      .then((response) => {
        if (response.status == 200) {
          if (url === '/evidence/file/decrypt') {
            resolve(response);
          } else {
            resolve(response.data);
          }
        } else {
          reject(response);
        }
      })
      .catch((error) => {
        console.error("Post Error:", error);
        resolve({
          data: "",
          msg: "出错了，请重试",
        });
      });
  });
};

//封装下put
api.put = function (url, params) {
  const token = sessionStorage.getItem("token")?.replace(/^(\s|")+|(\s|")+$/g, "");
  return new Promise((resolve, reject) => {
    axios({
      method: "PUT",
      url: config.baseURL + url,
      data: params,
      headers: {
        "Content-Type": "application/json",
        Authorization: token,
      },
    })
      .then((response) => {
        if (response.status == 200) {
          resolve(response.data);
        } else {
          reject(response);
        }
      })
      .catch((error) => {
        console.error("Put Error:", error);
        resolve({
          data: "",
          msg: "出错了，请重试",
        });
      });
  });
};

//封装下delete
api.delete = function (url) {
  const token = sessionStorage.getItem("token")?.replace(/^(\s|")+|(\s|")+$/g, "");
  return new Promise((resolve, reject) => {
    axios({
      method: "DELETE",
      url: config.baseURL + url,
      headers: {
        "Content-Type": "application/json",
        Authorization: token,
      },
    })
      .then((response) => {
        if (response.status == 200) {
          resolve(response.data);
        } else {
          reject(response);
        }
      })
      .catch((error) => {
        console.error("Delete Error:", error);
        resolve({
          data: "",
          msg: "出错了，请重试",
        });
      });
  });
};

//封装下get
api.get = function (url, params) {
  const token = sessionStorage.getItem("token")?.replace(/^(\s|")+|(\s|")+$/g, "");
  return new Promise((resolve, reject) => {
    axios({
      method: "GET",
      url: config.baseURL + url,
      params,
      headers: {
        "Content-Type": "application/json",
        "Authorization": token,
      },
    })
      .then((response) => {
        if (response.status == 200) {
          resolve(response.data);
        } else {
          reject(response);
        }
      })
      .catch((error) => {
        console.error("Get Error:", error);
        resolve({
          data: "",
          msg: "出错了，请重试",
        });
      });
  });
};

// http response 拦截器
axios.interceptors.response.use(
  (response) => {
    const { data = {} } = response;

    if (response.status === 200 && !data.success) {
      if (data.msg === "身份令牌已过期") {
        // 身份过期失效
        window.location.href = `${VITE_PREFIX}/login`;
        return response;
      }

      if (data.msg === "身份校验失败") {
        // 身份过期失效
        window.location.href = `${VITE_PREFIX}/404`;
        return response;
      }
    }
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return response;
  },
  (error) => {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    // Status 是 HTTP 状态码
    const status = get(error, "response.status")
    switch (status) {
      case 400:
        error.message = "请求错误"
        break
      case 401:
        // Token 过期时，直接退出登录并强制刷新页面（会重定向到登录页）
        store.userStore.logoutAction()
        error.message = "Token过期,请重新登录"
        router.push({ path: '/login' })
        // location.reload();
        break
      case 403:
        error.message = "拒绝访问"
        break
      case 404:
        error.message = "请求地址出错"
        break
      case 408:
        error.message = "请求超时"
        break
      case 500:
        error.message = "服务器内部错误"
        break
      case 501:
        error.message = "服务未实现"
        break
      case 502:
        error.message = "网关错误"
        break
      case 503:
        error.message = "服务不可用"
        break
      case 504:
        error.message = "网关超时"
        break
      case 505:
        error.message = "HTTP 版本不受支持"
        break
      default:
        break
    }
    // ElMessage.error(error.message)
    return Promise.reject(error);
  }
);

export default api;
